import re
import os


from model.WebsocketClientVO import WebsocketClientVO


class ArpService():
    def __init__(self, clientVO: WebsocketClientVO):
        self.cache = {}
        self.clientVO = clientVO
        self.update()

    def read(self, ip):
        if self.clientVO.dev:
            return ip
        if not ip:
            return None
        if ip not in self.cache:
            self.update()
        if ip not in self.cache:
            return None
        return self.cache[ip]

    def update(self):

        c = 'arp -a' if self.clientVO.dev else 'cat /proc/net/arp'
        output = os.popen(c)
        lines = output.readlines()
        pattern = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*?([0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){5})'
        for line in lines[1:]:  # 跳过标题行
            matches = re.findall(pattern, line.replace('(', '').replace(')', '').replace('at', ''))
            for k in matches:
                ip, mac = k
                self.cache[ip] = mac

    def lanMacList(self):
        if self.clientVO.dev:
            return []
        c = 'arp -a' if self.clientVO.dev else 'cat /proc/net/arp'
        output = os.popen(c)
        lines = output.readlines()
        a = []
        for line in lines:
            s = line.split(' ')
            if not s[-1].endswith('lan'):
                continue
            a.append(s[-2])
        return a


